package com.pkk.penguin.frame.know.java.interview.year2021.atguigu_20210226.lock;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import org.junit.Test;

/**
 * 读写锁
 *
 * @author peikunkun
 * @version V1.0
 * @date 2021-03-16 14:15
 **/
public class ReadWriteLockTest {


  //读写锁
  private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();


  private Map<Integer, Integer> map = new ConcurrentHashMap<>();


  @Test
  public void Administrator_21_20210316141908_() throws InterruptedException {
    System.out.println("欢迎使用单元测试方法【Administrator_21()_20210316141908】");
    System.out.println("此方法测试描述：【】");


    CountDownLatch countDownLatch=new CountDownLatch(20);

    for (int i = 0; i < 10; i++) {
      final Integer temp = i;
      new Thread(() -> {
        final WriteLock writeLock = lock.writeLock();
        try {
          writeLock.lock();
          System.out.println(Thread.currentThread().getName() + "开始写入" + temp);
          map.put(temp, temp);
          Thread.sleep(300);//写入耗时
          System.out.println(Thread.currentThread().getName() + "写入完成" + temp);
          countDownLatch.countDown();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          writeLock.unlock();
        }
      }).start();
    }

    for (int i = 0; i < 10; i++) {
      final Integer temp = i;
      new Thread(() -> {
        final ReadLock readLock = lock.readLock();
        try {
          readLock.lock();
          System.out.println(Thread.currentThread().getName() + "开始读取" + temp);
          final Integer integer = map.get(temp);
          Thread.sleep(300);//读取耗时
          System.out.println(Thread.currentThread().getName() + "读取完成" + integer);
          countDownLatch.countDown();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          readLock.unlock();
        }
      }).start();
    }

    countDownLatch.await();
  }

}
